// =====================================================================================
// 
//       Filename:  utils.cpp
// 
//    Description:  
// 
//        Version:  1.0
//        Created:  03/30/2010 03:21:09 PM
//       Revision:  none
//       Compiler:  g++
// 
//         Author:  tiger lee (tiger), tiger.lee@taodinet.com
//        Company:  Hangzhou TaodiNet Ltd.
// 
// =====================================================================================

// #####   HEADER FILE INCLUDES   ###################################################
#include	"utils.h"
#include	<stdio.h>
#include	<time.h>
#ifdef __WIN32__
#include	<winsock2.h>
#else
#include	<sys/time.h>
#include	<unistd.h>
#endif
#include	<string.h>
//#include	<iconv.h>

// #####   FUNCTION DEFINITIONS  -  EXPORTED FUNCTIONS   ############################
namespace lk_clock
{
    char str_now[64] = {'\0'};
    char str_ms[16] = {'\0'};

    char* now(char* fmt)
    {
#ifdef __WIN32__

#else
		time_t ts;
		struct tm* lt;
		ts = time(NULL);
		lt = localtime(&ts);
		strftime(str_now, sizeof(str_now), fmt, lt);
#endif
        return str_now;

    }

    char* now_ms()
    {
#ifdef __WIN32__

#else
		struct timeval tv;
		struct tm* lt;
		gettimeofday(&tv, NULL);
		lt = localtime(&(tv.tv_sec));
		strftime(str_now, sizeof(str_now), "%Y-%m-%d %H:%M:%S", lt);
		sprintf(str_ms, " %d", (int)tv.tv_usec);
		strcat(str_now, str_ms);
#endif
        return str_now;
    }

	INT64 milli_time()
	{
#ifdef __WIN32__
		return GetTickCount(); //test under windows. 
#else
		struct timeval tv;
		gettimeofday(&tv,NULL);
		return tv.tv_sec * 1000 + tv.tv_usec / 1000;
#endif
	}
}

void u_sleep(int us)
{
#ifdef __WIN32__
	Sleep(us);
#else
	usleep(us);
#endif
}
//const char* ConvGBK2UTF8(char* chFrom)
//{
//    static char chTo[1024];
//    char* pTo = chTo;
//    size_t nFromLeft = strlen(chFrom);
//    size_t nToLeft = 1024;
//    iconv_t cd;
//
//    memset(chTo, 0, 1024);
//    cd = iconv_open("utf8", "gbk");
//#ifdef __WIN32__
//    iconv(cd, (const char**)&chFrom, &nFromLeft, &pTo, &nToLeft);
//#else
//    iconv(cd, &chFrom, &nFromLeft, &pTo, &nToLeft);
//#endif
//    iconv_close(cd);
//    return chTo;
//}
//
//char* CopyString(char* dst, const char* src, int size)
//{
//    if (strcmp("undefined", dst) != 0) {
//         return strncpy(dst, dst, size);
//    } else {
//        return dst;
//    }
//}
